﻿using Compass.Wasm.Shared.Categories;
using Compass.Wasm.Shared.Wms;
using Compass.Wpf.ApiServices.Wms;
using System.Windows.Input;

namespace Compass.Wpf.ViewModels.Wms;

public class CargoesViewModel : NavigationViewModel
{
    #region ctor
    private readonly ICargoService _cargoService;
    private readonly ILocationService _locationService;
    private readonly IVendorService _vendorService;
    public CargoesViewModel(IContainerProvider provider) : base(provider)
    {
        _cargoService = provider.Resolve<ICargoService>();
        _locationService = provider.Resolve<ILocationService>();
        _vendorService = provider.Resolve<IVendorService>();
        CargoDto=new CargoDto();
        VendorDto=new VendorDto();
        ChangeLocationCommand = new DelegateCommand(ChangeLocation);
        AddLocationCommand = new DelegateCommand(AddLocation);
        DeleteLocationCommand = new DelegateCommand(DeleteLocation);

        VendorChangeCommand=new DelegateCommand(VendorChange);
        AddVendorCommand = new DelegateCommand(AddVendor);

        AddCargoCommand = new DelegateCommand(AddCargo);
        UpdateCargoCommand = new DelegateCommand<CargoDto>(UpdateCargo);
        DeleteCargoCommand = new DelegateCommand<CargoDto>(DeleteCargo);
        SaveCargoCommand = new DelegateCommand(SaveCargo);
        //OpenCsvCommand = new DelegateCommand(OpenCsv);
        //UpdateCommand = new DelegateCommand<string>(Update);
        UpdateRoles = "admin,whse,pur";
    }
    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }
    public DelegateCommand ChangeLocationCommand { get; }
    public DelegateCommand AddLocationCommand { get; }
    public DelegateCommand DeleteLocationCommand { get; }

    public DelegateCommand VendorChangeCommand { get; }
    public DelegateCommand AddVendorCommand { get; }

    public DelegateCommand AddCargoCommand { get; }
    public DelegateCommand<CargoDto> UpdateCargoCommand { get; }
    public DelegateCommand<CargoDto> DeleteCargoCommand { get; }
    public DelegateCommand SaveCargoCommand { get; }
    //public DelegateCommand OpenCsvCommand { get; }
    //public DelegateCommand<string> UpdateCommand { get; }
    #endregion

    #region 右侧展开栏属性
    private bool isRightDrawerOpen;
    /// <summary>
    /// 右侧窗口是否展开
    /// </summary>
    public bool IsRightDrawerOpen
    {
        get => isRightDrawerOpen;
        set { isRightDrawerOpen = value; RaisePropertyChanged(); }
    }
    private string rightDrawerTitle = null!;
    public string RightDrawerTitle
    {
        get => rightDrawerTitle;
        set { rightDrawerTitle = value; RaisePropertyChanged(); }
    }
    #endregion

    #region 属性
    private string location=string.Empty;
    public string Location
    {
        get => location;
        set { location = value; RaisePropertyChanged(); }
    }

    public ObservableRangeCollection<string> Locations { get; } = new();
    

    private Warehouse_e warehouse;
    public Warehouse_e Warehouse
    {
        get => warehouse;
        set
        {
            SetProperty(ref warehouse, value);
            SearchAll = false;
        }
    }

    private string[] warehouses = null!;
    public string[] Warehouses
    {
        get => warehouses;
        set { warehouses = value; RaisePropertyChanged(); }
    }

    private Area_e area;
    public Area_e Area
    {
        get => area;
        set
        {
            SetProperty(ref area, value);
            SearchAll = false;
        }
    }

    private string[] areas = null!;
    public string[] Areas
    {
        get => areas;
        set { areas = value; RaisePropertyChanged(); }
    }

    private string column;
    public string Column
    {
        get => column;
        set
        {
            SetProperty(ref column, value);
            SearchAll = false;
        }
    }

    private string[] columns = null!;
    public string[] Columns
    {
        get => columns;
        set { columns = value; RaisePropertyChanged(); }
    }

    private string row;
    public string Row
    {
        get => row;
        set
        {
            SetProperty(ref row, value);
            SearchAll = false;
        }
    }

    private string[] rows = null!;
    public string[] Rows
    {
        get => rows;
        set { rows = value; RaisePropertyChanged(); }
    }
    
    private string[] units = null!;
    public string[] Units
    {
        get => units;
        set { units = value; RaisePropertyChanged(); }
    }
    private string[] sbus = null!;
    public string[] Sbus
    {
        get => sbus;
        set { sbus = value; RaisePropertyChanged(); }
    }
    private string[] groups = null!;
    public string[] Groups
    {
        get => groups;
        set { groups = value; RaisePropertyChanged(); }
    }
    private string[] orderingWays = null!;
    public string[] OrderingWays
    {
        get => orderingWays;
        set { orderingWays = value; RaisePropertyChanged(); }
    }

    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value;
            RaisePropertyChanged();
            Filter();
        }
    }
    private bool searchAll;
    /// <summary>
    /// 全范围搜索
    /// </summary>
    public bool SearchAll
    {
        get => searchAll;
        set
        {
            SetProperty(ref searchAll, value);
            GetDataAsync();
        }
    }
    private CargoDto cargoDto;
    public CargoDto CargoDto
    {
        get => cargoDto;
        set { cargoDto = value; RaisePropertyChanged(); }
    }

    /// <summary>
    /// 用来选择物料
    /// </summary>
    private string keyword;
    public string Keyword
    {
        get => keyword;
        set
        {
            SetProperty(ref keyword, value);
            GetVendorDtos();
        }
    }
    private VendorDto vendorDto;
    public VendorDto VendorDto //当前选中的Vendor
    {
        get => vendorDto;
        set { vendorDto = value; RaisePropertyChanged(); }
    }

    public ObservableRangeCollection<CargoDto> CargoDtos { get; } = new();
    public ObservableRangeCollection<CargoDto> FilterCargoDtos { get; } = new();

    public ObservableRangeCollection<VendorDto> VendorDtos { get; } = new();
    #endregion

    #region 增删改查
    private void VendorChange()
    {
        //选择Cargo时，将值赋值给当前的Inventory
        var vendor = VendorDtos.SingleOrDefault(x => x.IsSelected);
        if (vendor == null) return;
        VendorDto=vendor;
    }

    private void AddVendor()
    {
        if (string.IsNullOrEmpty(CargoDto.Vendors))
        {
            CargoDto.Vendors = VendorDto.Number;
        }
        else
        {
            CargoDto.Vendors += $",{VendorDto.Number}";
        }
    }
    private void AddCargo()
    {
        CargoDto=new CargoDto();

        IsRightDrawerOpen = true;
        RightDrawerTitle = "添加物料";
    }

    private void UpdateCargo(CargoDto obj)
    {
        CargoDto=obj;

        IsRightDrawerOpen = true;
        RightDrawerTitle = "修改物料";
    }

    private async void DeleteCargo(CargoDto obj)
    {
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", $"确认删除物料：{obj.MtlNumber}, {obj.Description} 吗?");
        if (dialogResult.Result != ButtonResult.OK) return;
        await _cargoService.DeleteAsync(obj.Id.Value);
        GetDataAsync();
    }

    private async void SaveCargo()
    {
        //数据验证
        if (string.IsNullOrWhiteSpace(CargoDto.MtlNumber))
        {
            //发送提示
            Aggregator.SendMessage("物料号不能为空");
            return;
        }

        try
        {
            if (CargoDto.Id != null && CargoDto.Id.Value != Guid.Empty)
            {
                CargoDto.MtlNumber =CargoDto.MtlNumber.ToUpper();
                await _cargoService.UpdateAsync(CargoDto.Id.Value, CargoDto);
                Aggregator.SendMessage($"物料：{CargoDto.MtlNumber}，{CargoDto.Description}修改成功！");
                CargoDto.Id=Guid.Empty;
            }
            else
            {
                CargoDto.MtlNumber =CargoDto.MtlNumber.ToUpper();
                var cargoResult = await _cargoService.GetSingleByMtlNumberAsync(CargoDto.MtlNumber);
                if (cargoResult.Status)
                {
                    Aggregator.SendMessage($"请不要重复添加，物料：{CargoDto.MtlNumber}！");
                    return;
                }
                var locationResult = await _cargoService.GetSingleByLocationAsync(CargoDto.Location);
                if (locationResult.Status)
                {
                    Aggregator.SendMessage($"库位{CargoDto.Location}重复，请重新选择库位");
                    return;
                }
                await _cargoService.AddAsync(CargoDto);
                Aggregator.SendMessage($"物料：{CargoDto.MtlNumber},{CargoDto.Description}添加成功！");
                CargoDto.Id=Guid.Empty;
            }
            IsRightDrawerOpen = false;
            GetDataAsync();
        }
        catch (Exception e)
        {
            //发送错误报告
            Aggregator.SendMessage(e.Message);
        }
    }

    #endregion

    #region Location
    private async void GetLocations()
    {
        var ranks = $"{Column}-{Row}-";
        var result = await _locationService.GetAllByAreaAsync(Warehouse, Area, ranks);
        if (result.Status)
        {
            Locations.ReplaceRange(result.Result.Select(x => x.Name));
        }
    }

    private void ChangeLocation()
    {
        if(string.IsNullOrEmpty(Location))Aggregator.SendMessage("请选择库位！");
        CargoDto.Location = Location;
    }
    private void AddLocation()
    {
        CargoDto.Location = string.Join('_', CargoDto.Location,Location);
    }
    private void DeleteLocation()
    {
        CargoDto.Location = string.Empty;
    }
    #endregion

    #region 筛选
    private void Filter()
    {
        FilterCargoDtos.ReplaceRange(
            CargoDtos.Where(x =>
                string.IsNullOrEmpty(Search)||
                x.MtlNumber.Contains(Search, StringComparison.OrdinalIgnoreCase)||
                (!string.IsNullOrEmpty(x.Description)&&x.Description!.Contains(Search, StringComparison.OrdinalIgnoreCase)) ||
                (!string.IsNullOrEmpty(x.EnDescription)&&x.EnDescription!.Contains(Search, StringComparison.OrdinalIgnoreCase)) ||
                x.Group.ToString().Contains(Search,StringComparison.OrdinalIgnoreCase)||
                (!string.IsNullOrEmpty(x.Location)&&x.Location!.Contains(Search, StringComparison.OrdinalIgnoreCase)) ||
                (!string.IsNullOrEmpty(x.Vendors)&&x.Vendors!.Contains(Search, StringComparison.OrdinalIgnoreCase)) ||
                (!string.IsNullOrEmpty(x.Remarks)&&x.Remarks!.Contains(Search, StringComparison.OrdinalIgnoreCase))));
        //有的时候Remarks是null，导致调用Contains报错
    }
    #endregion

    #region 导航和初始化
    private void GetEnumNames()
    {
        //初始化一些枚举值
        Warehouses=Enum.GetNames(typeof(Warehouse_e));
        Areas=Enum.GetNames(typeof(Area_e));
        Columns = Enumerable.Range(1, 9).ToArray().ToList().ConvertAll<string>(x => x.ToString()).ToArray();
        Rows = Enumerable.Range(1, 9).ToArray().ToList().ConvertAll<string>(x => x.ToString()).ToArray();
        Column = Columns[0];
        Row = Rows[0];
        Units=Enum.GetNames(typeof(Unit_e));
        Sbus=Enum.GetNames(typeof(Sbu_e));
        Groups=Enum.GetNames(typeof(Group_e));
        OrderingWays=Enum.GetNames(typeof(OrderingWay_e));
    }
    
    private async void GetDataAsync()
    {
        if (SearchAll)
        {
            var result = await _cargoService.GetAllAsync();
            if (result.Status)
            {
                CargoDtos.ReplaceRange(result.Result);
            }
        }
        else
        {
            var ranks = $"{Column}-{Row}-";
            var result = await _cargoService.GetAllByAreaAsync(Warehouse, Area,ranks);
            if (result.Status)
            {
                CargoDtos.ReplaceRange(result.Result);
            }
        }
        Filter();
        GetLocations();
    }

    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);

        GetEnumNames();
        GetDataAsync();
        GetVendorDtos();
    }


    #endregion

    #region 搜索供应商
    private async void GetVendorDtos()
    {
        VendorDtos.ReplaceRange((await _vendorService.GetTop5ByKeywordAsync(Keyword)).Result);
    }
    #endregion
}